import axios from 'axios' // 引入axios
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_SERVICE_URL as string, // "http://127.0.0.1:4523/mock/697928", // apiFox Mock
  // baseURL: 'http://124.223.107.112',
  timeout: 10000,
})

service.interceptors.request.use(config => {
  config.headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    ...config.headers,
  }
  return config
})

service.interceptors.response.use(
  response => {
    // 正确, 返回消息体 ~~取整
    if (~~(response.status / 100) == 2) {
      if (response.headers.msg) {
        response.data.msg = decodeURI(response.headers.msg)
      }
      // 每次请求成功给出提示
      // ElMessage({
      //     showClose: false, // 不显示关闭按钮
      //     message: response.data.msg,// || decodeURI(response.headers.msg),
      //     type: 'success'
      // })
    } else {
      ElMessage({
        showClose: true,
        message: response.data.msg || decodeURI(response.headers.msg),
        type: 'error',
      })
    }
    return response
  },
  error => {
    ElMessage({
      showClose: true,
      message: error,
      type: 'error',
    })
    return error
  },
)

export default service
